package com.thunder.ktv.scoreengine2test.audio;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.util.Log;

import com.thunder.ktv.scoreengine2sdk.ScoreEngine2;

/**
 * 录音数据提供者（独立文件）
 */
public class AudioRecordProvider implements IAudioProvider{
    private static final String TAG = "AudioRecordProvider";
    private static final int SAMPLE_RATE = ScoreEngine2.SAMPLE_RATE;
    private static final int CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_MONO;
    private static final int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;

    private AudioRecord audioRecord;
    private volatile boolean isPaused = false;
    private final int bufferSize;

    public AudioRecordProvider() {
        bufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT);
        try {
//            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
//                // TODO: Consider calling
//                //    ActivityCompat#requestPermissions
//                // here to request the missing permissions, and then overriding
//                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
//                //                                          int[] grantResults)
//                // to handle the case where the user grants the permission. See the documentation
//                // for ActivityCompat#requestPermissions for more details.
//                return false;
//            }
            audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
                    SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT, bufferSize);
        } catch (Exception e) {
            Log.e(TAG, "初始化录音失败", e);
        }
    }

    public void start() {
        if (audioRecord != null && audioRecord.getState() == AudioRecord.STATE_INITIALIZED) {
            audioRecord.startRecording();
            isPaused = false;
        }
    }
    
    public void pause() {
        isPaused = true;
    }
    
    public void resume() {
        isPaused = false;
    }
    
    public void stop() {
        if (audioRecord != null) {
            audioRecord.stop();
        }
    }
    
    public void release() {
        stop();
        if (audioRecord != null) {
            audioRecord.release();
            audioRecord = null;
        }
    }
    
    public int read(short[] buffer) {
        if (isPaused || audioRecord == null) {
            return -1;
        }
        if(audioRecord.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING)
            return audioRecord.read(buffer, 0, buffer.length);
        return -1;
    }
    
    public int getSampleRate() {
        return SAMPLE_RATE;
    }
    
    public int getChannelCount() {
        return 1;
    }
    
    public int getBitDepth() {
        return 16;
    }
} 